package edu.zju.gis.dbfg.server.interceptor;

import com.google.common.net.HttpHeaders;
import com.google.gson.Gson;
import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.common.constant.CodeConstants;
import edu.zju.gis.dbfg.server.config.CommonSetting;
import edu.zju.gis.dbfg.server.constant.Term;
import edu.zju.gis.dbfg.server.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 进行用户登录状态验证
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/user/login**");
        addInterceptor.excludePathPatterns("/user/init");
        addInterceptor.excludePathPatterns("/user/register");
        addInterceptor.excludePathPatterns("/static/**");
        addInterceptor.addPathPatterns("/**");
    }

    //Let the sessionId be same.
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("*").allowedHeaders("*")
                .allowCredentials(true)
                .exposedHeaders(HttpHeaders.SET_COOKIE)
                .exposedHeaders(HttpHeaders.ORIGIN).maxAge(3600L);
    }

    private static class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

            HttpSession session = request.getSession();
//            session.setAttribute("userId","2");
//            session.setAttribute(Term.USERID, "1");
//            session.setAttribute(Term.USERNAME, "test");
//            session.setAttribute(Term.USERROLE, "user");
            if (session.getAttribute("userId") != null) {
                return true;
            } else {
                HttpURLConnection connection = null;
                InputStream is = null;
                BufferedReader br = null;
                String userId = "-1";
                try {
//                    URL url = new URL("http://121.89.211.142:9400/dbfg/user/status");
                    URL url = new URL("http://192.168.1.5:9400/dbfg/user/status");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(150);
                    connection.setReadTimeout(600);
                    String sessionId = "-1";
                    for(Cookie ck : request.getCookies())
                    {
//                        String ckname=ck.getName();
//                        String name="sessionid";
//                        boolean res=ckname.equals(name);
                        if(ck.getName().equals("sessionid"))
                        {
                            sessionId="sessionid="+ck.getValue();
                            break;
                        }
                    }
                    connection.setRequestProperty("Cookie",sessionId);
                    connection.connect();
                    if (connection.getResponseCode() == 200) {
                        is = connection.getInputStream();
                        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        StringBuffer sbf = new StringBuffer();
                        String temp = null;
                        while ((temp = br.readLine()) != null) {
                            System.out.println("temp的值是："+temp);
                            sbf.append(temp);
                            sbf.append("\r\n");
                        }
                        org.json.JSONObject user = new org.json.JSONObject(sbf.toString());
                        System.out.println(user);
                        userId = user.getJSONObject("body").getString("id");
                    }
                    connection.disconnect();
                    if (!userId.equals("-1")) {
                        session.setAttribute("userId", userId);
                        return true;
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            Result<String> result =
                    new Result<>(CodeConstants.VALIDATE_ERROR, "user has not log in yet");
            response.setContentType("application/json;charset=utf-8");
            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(result));
            return false;
        }
    }
}